package com.njbw.tool;

import lombok.extern.log4j.Log4j2;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.TimeUnit;

@Log4j2
public class ThreadPoolUtil {

    private ThreadPoolUtil() {}

    public static void shutDownPool(ExecutorService pool,
                                    int shutDownTimeout, int shutDownNowTimeout, TimeUnit timeUnit) {
        pool.shutdown();
        try {
            if (!pool.awaitTermination(shutDownTimeout, timeUnit)) {
                pool.shutdownNow();
                if (!pool.awaitTermination(shutDownNowTimeout, timeUnit)) {
                    log.error("ThreadPoolUtil.shutDownPool.error");
                }
            }
        } catch (InterruptedException e) {
            // 外部线程如果死了，我们应该进行一些什么样的调整
            log.error("ThreadPoolUtil.shutDownPool.interrupted.error: {}", e.getMessage(), e);
            pool.shutdownNow();
            Thread.currentThread().interrupt(); // 把线程重启的标志位打断
        }
    }
}
